package logic

import (
	"cart_srv/cart"
	"cart_srv/internal/svc"
	"cart_srv/model/mysql"
	"cart_srv/model/redis"
	"context"
	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsAddLogic {
	return &GoodsAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodsAddLogic) GoodsAdd(in *cart.GoodsAddRequest) (*cart.GoodsAddResponse, error) {
	// todo: add your logic here and delete this line
	var good mysql.Goods
	mysql.DB.Where("goods_name=?", in.GoodsName).Limit(1).Find(&good)
	if good.ID != 0 {
		logx.Error("该商品已发布")
		return nil, nil
	}
	goods := mysql.Goods{
		GoodsName:  in.GoodsName,
		GoodsPrice: float64(in.GoodsPrice),
		GoodsStock: int(in.GoodsStock),
		GoodsCover: in.GoodsCover,
	}
	mysql.DB.Debug().Create(&goods)
	redis.SyncGoodsStock(int64(goods.ID), int(in.GoodsStock))
	return &cart.GoodsAddResponse{Id: int64(goods.ID)}, nil
}
